import Packet from "../net/Packet"
import GoodsItem from './GoodsItem'

// 登录成功
export default class RoleLoginOk {
	/**
	 * @param uid 玩家ID
	 * @param uname 玩家昵称
	 * @param goodsItems 物品列表
	 * @param video 语音
	 */
	public constructor(public uid: number, public uname: string, public goodsItems: GoodsItem[], public video?: Uint8Array) { }

	public encode(): Packet {
		const packet = this._encode()
		packet.Encode(1020)
		return packet
	}

	public encodeMsg(): ByteBuffer {
		return this._encode().GetBuffer()
	}

	public static decode(packet: Packet): RoleLoginOk {
		const uid = packet.ReadUint()
		const uname = packet.ReadString()
		const goodsItems = []
		const goodsItemsCount = packet.ReadUshort()
		for (let i = 0; i < goodsItemsCount; i++) {
			goodsItems.push(GoodsItem.decode(packet))
		}
		const videoFlag = packet.ReadByte()
		let video: Uint8Array
		if (videoFlag == 1) {
			video = packet.ReadBin()
		}
		return new RoleLoginOk(uid, uname, goodsItems, video)
	}

	private _encode(): Packet {
		const packet = new Packet()
		packet.WriteUint(this.uid)
		packet.WriteString(this.uname)
		const goodsItemsCount = this.goodsItems.length
		packet.WriteUshort(goodsItemsCount)
		for (let i = 0; i < goodsItemsCount; i++) {
			const xxx = this.goodsItems[i]
			packet.WriteBuffer(xxx.encodeMsg())
		}
		if (this.video) {
			packet.WriteByte(1)
			packet.WriteBin(this.video)
		} else {
			packet.WriteByte(0)
		}
		return packet
	}
}
